﻿using System;
using System.Collections.Generic;

namespace MyCommon
{
    /// <summary>
    /// 针对带有主键的实体类实例的相等比较器，只要主键相等就认为相等
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <typeparam name="TKey">主键类型</typeparam>
    public class EntityEqualityComparer<T, TKey> : EqualityComparer<T>
    {
        Func<T, TKey> m_keySelector;
        /// <summary>
        /// 构造EntityEqualityComparer
        /// </summary>
        /// <param name="keySelector">返回主键委托</param>
        public EntityEqualityComparer(Func<T, TKey> keySelector)
        {
            m_keySelector = keySelector;
        }
        /// <summary>
        /// 比较方法
        /// </summary>
        /// <param name="x">第一个值</param>
        /// <param name="y">第二个值</param>
        /// <returns>相等为true</returns>
        public override bool Equals(T x, T y)
        {
            var xKey = m_keySelector(x);
            var yKey = m_keySelector(y);
            return EqualityComparer<TKey>.Default.Equals(xKey, yKey);
        }
        /// <summary>
        /// 要为其获取哈希代码的对象。
        /// </summary>
        /// <param name="obj">指定对象</param>
        /// <returns>哈希代码</returns>
        public override int GetHashCode(T obj)
        {
            return EqualityComparer<TKey>.Default.GetHashCode(m_keySelector(obj));
        }
    }
}
